<script>
	import {
		apiUrl
	} from '@/api/base.js'
	export default {
		onLaunch: function() {
			var that = this;			
		},
		onShow: function() {
			// if(uni.getStorageSync("userInfo")){
			// 	this.checkType()
			// }
		},
		onHide: function() {

		},
		methods: {
			//判断是否登录
			checkType: function(cb) {
				var that = this
				uni.request({
					url: apiUrl+"addons/car/user/getType",
					data:{
						token: uni.getStorageSync('token'),
						user_id:uni.getStorageSync("userInfo").id
					},
					method:"POST",
					success:(res)=>{					
						let data = res.data.data
						if(data.type!=uni.getStorageSync("userInfo").type){
							uni.showModal({
							    title: '提示',
							    content: '用户类型已改变，需重新登录！',
							    success: function (res) {
							        if (res.confirm) {
							            uni.navigateTo({
							            	url: '/pages/my/login'					
							            });
							        } else if (res.cancel) {
							            console.log('用户点击取消');
							        }
							    }
							});
						}
					},
					fail:(res)=>{
						console.log(res)
					}
					
				})
			},
			//登录
			login: function(cb) {
				var that = this;
				var token = uni.getStorageSync('token') || '';
				//调用登录接口
				uni.login({
					success: function(res) {
						if (res.code) {
							that.code = res.code
						} else {
							that.showLoginModal(cb);
						}
					}
				});
				//发起网络请求
				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: function(ures) {
						uni.request({
							url: apiUrl + 'addons/car/user/login',
							data: {
								code: that.code,
								rawData: ures.rawData,
								token: token
							},
							method: 'post',
							header: {
								"Content-Type": "application/x-www-form-urlencoded",
							},
							success: function(lres) {
								var response = lres.data
								if (response.code == 1) {
									uni.setStorageSync('userInfo', response
										.data.userInfo);
									uni.setStorageSync('token', response
										.data.userInfo.token);
									wx.navigateBack({
									  delta: 1
									})
								} else {
									uni.setStorageSync('token', '');
									console.log("用户登录失败")
									that.showLoginModal(cb);
								}
							},
							fail: function(res) {
								console.log(res)
							}
						});
					},
					fail: function(res) {
						//that.showLoginModal(cb);
						console.log(res)
					}
				});
			},
			//显示登录或授权提示
			showLoginModal: function(cb) {
				var that = this;
				if (!that.globalData.userInfo) {
					//获取用户信息
					uni.getSetting({
						success: function(sres) {
							if (sres.authSetting['scope.userInfo']) {
								uni.showModal({
									title: '温馨提示',
									content: '当前无法获取到你的个人信息，部分操作可能受到限制',
									confirmText: "重新登录",
									cancelText: "暂不登录",
									success: function(res) {
										if (res.confirm) {
											that.login(cb);
										} else {
											console.log('用户暂不登录');
										}
									}
								});
							} else {
								uni.showModal({
									title: '温馨提示',
									content: '当前无法获取到你的个人信息，部分操作可能受到限制',
									confirmText: "去授权",
									cancelText: "暂不授权",
									success: function(res) {
										if (res.confirm) {
											uni.navigateTo({
												url: '/page/my/setting?type=getuserinfo',
											});
											return false;
											uni.openSetting({
												success: function(sres) {
													that.check(cb);
												}
											});
										} else {
											console.log('用户暂不授权');
										}
									}
								});
							}
						}
					});
				} else {
					typeof cb == "function" && cb(that.globalData.userInfo);
				}
			},
			//发起网络请求
			request: function(url, data, success, error) {
				var that = this;
				if (typeof data == 'function') {
					success = data;
					error = success;
					data = {};
				}
				if (this.globalData.userInfo) {
					data['user_id'] = this.globalData.userInfo.id;
					data['token'] = this.globalData.userInfo.token;
				}
				//移除最前的/
				while (url.charAt(0) === '/')
					url = url.slice(1);
				this.loading(true);
				let cookie = uni.getStorageSync('cookieKey');
				let header = {
					"Content-Type": "application/x-www-form-urlencoded"
				};
				if (cookie) {
					header.Cookie = cookie;
				}
				if (this.globalData.__token__) {
					data.__token__ = this.globalData.__token__;
				}
				data._ajax = 1;
				uni.request({
					url: this.apiUrl + url,
					data: data,
					method: 'post',
					header: header,
					success: function(res) {
						that.loading(false);
						var code, msg, json;
						if (res && res.header) {
							if (res.header['Set-Cookie']) {
								uni.setStorageSync('cookieKey', res.header[
									'Set-Cookie']); //保存Cookie到Storage
							}
							if (res.header['__token__']) {
								that.globalData.__token__ = res.header['__token__'];
							}
						}
						if (res.statusCode === 200) {
							json = res.data;
							if (json.code === 1) {
								typeof success === 'function' && success(json.data, json);
							} else {
								typeof error === 'function' && error(json.data, json);
							}
						} else {
							json = typeof res.data === 'object' ? res.data : {
								code: 0,
								msg: '发生一个未知错误',
								data: null
							};
							typeof error === 'function' && error(json.data, json);
						}
					},
					fail: function(res) {
						that.loading(false);
						console.log("fail:", res);
						typeof error === 'function' && error(null, {
							code: 0,
							msg: '',
							data: null
						});
					}
				});
			},
			//构造CDN地址
			cdnurl: function(url) {
				return url.toString().match(/^https?:\/\/(.*)/i) ? url : this.globalData.config.upload.cdnurl + url;
			},
			//文本提示
			info: function(msg, cb) {
				uni.showToast({
					title: msg,
					icon: 'none',
					duration: 2000,
					complete: function() {
						typeof cb == "function" && cb();
					}
				});
			},
			//成功提示
			success: function(msg, cb) {
				uni.showToast({
					title: msg,
					icon: 'success',
					image: '/assets/images/ok.png',
					duration: 2000,
					complete: function() {
						typeof cb == "function" && cb();
					}
				});
			},
			//错误提示
			error: function(msg, cb) {
				uni.showToast({
					title: msg,
					icon: 'none',
					// image: '/assets/images/error.png',
					duration: 2000,
					complete: function() {
						typeof cb == "function" && cb();
					}
				});
			},
			//警告提示
			warning: function(msg, cb) {
				uni.showToast({
					title: msg,
					image: '/assets/images/warning.png',
					duration: 2000,
					complete: function() {
						typeof cb == "function" && cb();
					}
				});
			},
			//Loading
			loading: function(msg) {
				if (typeof msg == 'boolean') {
					if (!msg) {
						if (!this.si) {
							return;
						}
						clearTimeout(this.si);
						uni.hideLoading({});
						return;
					}
				}
				msg = typeof msg == 'undefined' || typeof msg == 'boolean' ? '加载中' : msg;
				this.globalData.loading = true;
				if (this.si) {
					return;
				}
				this.si = setTimeout(function() {
					uni.showLoading({
						title: msg
					});
				}, 300);

			}
		},
		//全局信息
		globalData: {
			userInfo: null,
			config: null,
			token: ''
		}
	}
</script>

<style>
	/*每个页面公共css */
	@font-face {
		font-family: 'iconfont';
		/* project id 1940415 */
		src: url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.eot');
		src: url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.eot?#iefix') format('embedded-opentype'),
			url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.woff2') format('woff2'),
			url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.woff') format('woff'),
			url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.ttf') format('truetype'),
			url('https://at.alicdn.com/t/font_1940415_ls6ic8x3j5f.svg#iconfont') format('svg');
	}

	.iconfont {
		display: inline-block;
		font-family: "iconfont" !important;
		font-size: 16px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	page {
		background-color: #f7f7f7;
		color: #333;
	}

	image {
		vertical-align: top;
	}

	.placeholder {
		color: #a9a9a9;
	}

	page button {
		border: none !important;
		border-radius: 0;
	}

	button:after {
		display: none;
	}

	table {
		width: 100% !important;
	}

	/* 重置指示点位置 */
	.credit-banner-block .uni-swiper-dots-horizontal {
		bottom: 48rpx !important;
	}

	/*设置radio的尺寸*/
	.radio-size-base {
		transform: scale(0.8)
	}

	.radio-size-middle {
		transform: scale(1)
	}

	.radio-size-lg {
		transform: scale(1.2)
	}

	/* 列表container绝对定位（避免h5上显示半截） */
	.container-fixed-flex {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
	}

	uni-image {
		pointer-events: auto;
	}

	image,
	img {
		vertical-align: middle;
	}

	.banner .uni-swiper-dots-horizontal {
		bottom: 20px !important;
	}
</style>
